package ar.unc.famaf.pln.giveselector.selectors;

import give.formula.Atom;
import give.formula.Orientation;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import ar.unc.famaf.pln.giveselector.context.Context;
import ar.unc.famaf.pln.giveselector.context.Utterance;

/**
 * This Selector class chooses all the Utterances whose
 * reaction shares an initial segment with the future actions
 * of the context.
 * 
 * @author david ( david.racca@gmail.com )
 *
 */
public class FreeSelector extends DefaultSelector {

	protected static final boolean DEBUG = false;
	

	public FreeSelector(Map<String, Set<Utterance>> utterances) {
		super(utterances);
	}

	@SuppressWarnings("unused")
	@Override
	public Set<Utterance> selectUtterances(String worldName, Context context) {
		if (DEBUG)
		{
			System.out.println("==========================================");
			System.out.println("===== STARTING SELECTION");
		}

		Set<Utterance> selectedUtterances = new HashSet<Utterance>();
		if (!utterances.containsKey(worldName))
		{
			System.out.println(worldName + " is not supported by the NLG Server: supported worlds are "
					+ utterances.keySet());
			System.out.println(context.getFutureActions());
			return new HashSet<Utterance>();
		}

		for(Utterance candidate : utterances.get(worldName))
		{
			List<Atom> planResponse = candidate.getResponse().getDiscretizedActions();
			List<Atom> plannedActions = context.getFutureActions();

			boolean allMatched = true;
			for(int j = 0; j < Math.min(planResponse.size(), plannedActions.size()); j++)
			{
				Atom responseAction = planResponse.get(j);
				Atom planAction = plannedActions.get(j);
				if (!responseAction.equals(planAction))
				{
					allMatched = false;
					break;
				}
			}

			if (allMatched && !planResponse.isEmpty())
			{
				selectedUtterances.add(candidate);
				if (DEBUG)
				{
					System.out.println("Next " + plannedActions.size() + " planned actions: " + plannedActions);
					System.out.println(candidate);
				}
				Context c1 = candidate.getContext();
				Orientation o2 = context.getOrientation();
				if (Math.abs(c1.getOrientation().getAngleTo(o2)) > (Math.PI / 4) && DEBUG)
					System.out.println("Different orientation");
				if (DEBUG)
					System.out.println("-----------------------------------");
			}
		}

		if (DEBUG)
		{
			System.out.println("==========================================");
			System.out.println("==========================================");
		}

		if (selectedUtterances.isEmpty() && DEBUG)
			System.out.println("No utterances for plan: " + context.getNFutureAction(10));
		return selectedUtterances;
	}

}
